//
//  PPProfileHeaderView.m
//  pickpic
//
//  Created by GaoYongyue on 16/9/11.
//  Copyright © 2016年 MicroDream. All rights reserved.
//

#import "PPProfileHeaderView.h"
#import "PPFollowingUserListViewController.h"
#import "PPFanUserListViewController.h"
#import "PPUserInfoViewController.h"
#import "PPProfileSettingViewController.h"
#import "PPFollowActionView.h"
#import "PPProfileMoreActionSheet.h"
#import "PPComplainViewController.h"
#import "PPFriendsTimelineCellMoreActionSheet.h"

#import "PPSocializationManager.h"

@interface PPProfileHeaderView ()
@property (weak, nonatomic) IBOutlet UIImageView *avatarView;
@property (weak, nonatomic) IBOutlet UIButton *editButton;
@property (weak, nonatomic) IBOutlet UIButton *moreButton;
@property (weak, nonatomic) IBOutlet UILabel *genderLabel;
@property (weak, nonatomic) IBOutlet UILabel *descLabel;
@property (strong, nonatomic) IBOutlet UILabel *albumLabel;
@property (weak, nonatomic) IBOutlet UILabel *followedLabel;
@property (weak, nonatomic) IBOutlet UILabel *followingLabel;

@property (nonatomic, strong) PPAccountProfiles *profiles;
@end
@implementation PPProfileHeaderView

- (void)awakeFromNib
{
    [super awakeFromNib];

    _editButton.layer.masksToBounds = YES;
    _editButton.layer.cornerRadius = 4.f;
    _editButton.layer.borderWidth = 1;

    _moreButton.layer.masksToBounds = YES;
    _moreButton.layer.cornerRadius = 4.f;
    _moreButton.layer.borderWidth = 1;
    _moreButton.layer.borderColor = [UIColor colorWithRGBHex:0x808080].CGColor;

    __weak typeof(self)weakSelf = self;
    [_followingLabel setActionBlock:^(UIControl *control) {
        [MobClick event:@"84"];
        PPFollowingUserListViewController *userListViewContoller = [[PPFollowingUserListViewController alloc] init];
        userListViewContoller.userID = weakSelf.profiles.userID;
        [weakSelf.delegateViewController.navigationController pushViewController:userListViewContoller animated:YES];
    } forEvent:UIControlEventTouchUpInside];

    [_followedLabel setActionBlock:^(UIControl *control) {
        [MobClick event:@"83"];
        PPFanUserListViewController *userListViewContoller = [[PPFanUserListViewController alloc] init];
        userListViewContoller.userID = weakSelf.profiles.userID;
        [weakSelf.delegateViewController.navigationController pushViewController:userListViewContoller animated:YES];
    } forEvent:UIControlEventTouchUpInside];

    [_avatarView setActionBlock:^(UIControl *control) {
        PPUserInfoViewController *userInfoViewController = [[UIStoryboard storyboardWithName:@"User" bundle:nil] instantiateViewControllerWithIdentifier:@"PPUserInfoViewController"];
        userInfoViewController.userID = weakSelf.profiles.userID;
        [weakSelf.delegateViewController.navigationController pushViewController:userInfoViewController animated:YES];
    } forEvent:UIControlEventTouchUpInside];
}

- (IBAction)editButtonDidPress:(id)sender {
    if ([_profiles.userID isEqualToString:DGCurrentAccount.userID])
    {
        //编辑个人资料页
        [MobClick event:@"69"];
        PPProfileSettingViewController *vc = [[UIStoryboard storyboardWithName:@"Setting" bundle:nil] instantiateViewControllerWithIdentifier:@"PPProfileSettingViewController"];
        [self.delegateViewController.navigationController pushViewController:vc animated:YES];
    }
    else if ([_profiles.relationship integerValue] == 0 || [_profiles.relationship integerValue] == 1)
    {
        //已关注
        //取消关注
        [MobClick event:@"71"];
        PPFollowActionView *actionView = [[NSBundle mainBundle] loadNibNamed:@"PPFollowActionView" owner:nil options:nil].firstObject;
        actionView.frame = CGRectMake(0, self.delegateViewController.navigationController.view.height - actionView.height, self.delegateViewController.navigationController.view.width, actionView.height);

        DGPopoverView *popoverView = [[DGPopoverView alloc] initWithContainerView:self.delegateViewController.navigationController.view contentView:actionView options:DGPopoverViewAnimationOptionUpward backgroundStyle:DGPopoverViewBackgroundStyleDimmed];

        __weak typeof(self) weakSelf = self;
        __weak typeof(popoverView) weakPopover = popoverView;
        [actionView.cancelButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:nil];
        } forControlEvents:UIControlEventTouchUpInside];

        [actionView.unfollowButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:^{
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:weakSelf.delegateViewController.view animated:YES];
                [PPNetworkService unFollow:weakSelf.profiles.userID callback:^(id data, NSError *error) {
                    [hud hide:YES];
                    if (data)
                    {
                        //取消关注成功
                        weakSelf.profiles.relationship = @(2);
                        weakSelf.editButton.layer.borderColor = [UIColor colorWithRGBHex:0x808080].CGColor;
                        weakSelf.editButton.backgroundColor = [UIColor whiteColor];
                        [weakSelf.editButton setTitle:@"+ 关注" forState:UIControlStateNormal];

                        [[NSNotificationCenter defaultCenter] postNotificationName:PPRelationshipDidChangeNotification object:weakSelf.profiles.userID];
                    }
                    else
                    {
                        [weakSelf.delegateViewController.view toastMessage:error.networkPrompt duration:1.f];
                    }
                }];

            }];
        } forControlEvents:UIControlEventTouchUpInside];

        [popoverView displayAnimated:YES completion:nil];
    }
    else
    {
        //+ 关注
        [MobClick event:@"70"];
        __weak typeof(self)weakSelf = self;
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:_delegateViewController.view animated:YES];
        [PPNetworkService follow:_profiles.userID callback:^(id data, NSError *error) {
            [hud hide:YES];
            if (data)
            {
                weakSelf.profiles.relationship = @([data integerValue]);
                weakSelf.editButton.backgroundColor = [UIColor colorWithRGBHex:0xfede17];
                weakSelf.editButton.layer.borderColor = [UIColor whiteColor].CGColor;
                [weakSelf.editButton setTitle:@"已关注" forState:UIControlStateNormal];

                [[NSNotificationCenter defaultCenter] postNotificationName:PPRelationshipDidChangeNotification object:_profiles.userID];
            }
            else
            {
                [weakSelf.delegateViewController.navigationController.view toastMessage:error.networkPrompt duration:1.0];
            }
        }];
    }

}

- (IBAction)moreButtonDidPress:(id)sender {
    [MobClick event:@"72"];
    if ([_profiles.userID isEqualToString:DGCurrentAccount.userID])
    {
        PPProfileMoreActionSheet *actionView = [[NSBundle mainBundle] loadNibNamed:@"PPProfileMoreActionSheet" owner:nil options:nil].firstObject;
        actionView.frame = CGRectMake(0, self.delegateViewController.navigationController.view.height - actionView.height, self.delegateViewController.navigationController.view.width, actionView.height);

        DGPopoverView *popoverView = [[DGPopoverView alloc] initWithContainerView:self.delegateViewController.navigationController.view contentView:actionView options:DGPopoverViewAnimationOptionUpward backgroundStyle:DGPopoverViewBackgroundStyleDimmed];

        __weak typeof(self) weakSelf = self;
        __weak typeof(popoverView) weakPopover = popoverView;
        [actionView.cancelButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:nil];
        } forControlEvents:UIControlEventTouchUpInside];

        [actionView.shareButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:^{
                [weakSelf didSelectShareCard];
            }];
        } forControlEvents:UIControlEventTouchUpInside];
        [popoverView displayAnimated:YES completion:nil];
    }
    else
    {
        PPFriendsTimelineCellMoreActionSheet *actionView = [[NSBundle mainBundle] loadNibNamed:@"PPFriendsTimelineCellMoreActionSheet" owner:nil options:nil].firstObject;
        actionView.frame = CGRectMake(0, self.delegateViewController.navigationController.view.height - actionView.height, self.delegateViewController.navigationController.view.width, actionView.height);

        DGPopoverView *popoverView = [[DGPopoverView alloc] initWithContainerView:self.delegateViewController.navigationController.view contentView:actionView options:DGPopoverViewAnimationOptionUpward backgroundStyle:DGPopoverViewBackgroundStyleDimmed];

        __weak typeof(self) weakSelf = self;
        __weak typeof(popoverView) weakPopover = popoverView;
        [actionView.cancelButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:nil];
        } forControlEvents:UIControlEventTouchUpInside];

        [actionView.shareButton setActionBlock:^(UIControl *control) {
            //分享名片
            [weakPopover dismissAnimated:YES completion:^{
                [weakSelf didSelectShareCard];
            }];
        } forControlEvents:UIControlEventTouchUpInside];

        [actionView.complainButton setActionBlock:^(UIControl *control) {
            //投诉
            [weakPopover dismissAnimated:YES completion:^{
                PPComplainViewController *vc = [[UIStoryboard storyboardWithName:@"Setting" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"PPComplainViewController"];
                vc.type = @4;
                vc.relationID = [NSNumber numberWithLongLong:[weakSelf.profiles.userID longLongValue]];
                [weakSelf.delegateViewController.navigationController pushViewController:vc animated:YES];
            }];
            
        } forControlEvents:UIControlEventTouchUpInside];
        [popoverView displayAnimated:YES completion:nil];
    }

}

- (void)didSelectShareCard {

    __block NSError *error_ = nil;
    __block NSString *title = nil;
    __block NSString *subtitle = nil;
    __block NSString *URLString = nil;
    __block UIImage *image_ = nil;


    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.delegateViewController.navigationController.view animated:YES];

    dispatch_group_t group = dispatch_group_create();

    dispatch_group_enter(group);
    [PPNetworkService getCardShareInfoWithTargetUser:@([_profiles.userID longLongValue]) callback:^(id data, NSError *error) {
        if(error != nil) {
            error_ = error;
        } else {
            title = [data validStringForKey:@"title"];
            subtitle = [data validStringForKey:@"title2"];
            URLString = [data validStringForKey:@"url"];
        }

        dispatch_group_leave(group);
    }];

    dispatch_group_notify(group, dispatch_get_main_queue(), ^{

        [hud hide:YES];

        if(error_ != nil) {
            [self.delegateViewController.navigationController.view toastMessage:error_.networkPrompt];
        } else {
            [self sharePictureWithTitle:title subtitle:subtitle url:URLString image:image_];
        }
    });
}

- (void)sharePictureWithTitle:(NSString *)title subtitle:(NSString *)subtitle url:(NSString *)url image:(UIImage *)image {

    UIView *actionView = nil;

    if([[PPSocializationManager sharedInstance] support:PPSocializationTypeWeixin] && [[PPSocializationManager sharedInstance] support:PPSocializationTypeQQ]) {
        actionView = [[[NSBundle mainBundle] loadNibNamed:@"PPAlbumShareActionView" owner:nil options:nil] safeObjectAtIndex:4];
    } else if([[PPSocializationManager sharedInstance] support:PPSocializationTypeWeixin]) {
        actionView = [[[NSBundle mainBundle] loadNibNamed:@"PPAlbumShareActionView" owner:nil options:nil] safeObjectAtIndex:5];
    } else if([[PPSocializationManager sharedInstance] support:PPSocializationTypeQQ]) {
        actionView = [[[NSBundle mainBundle] loadNibNamed:@"PPAlbumShareActionView" owner:nil options:nil] safeObjectAtIndex:6];
    } else {
        actionView = [[[NSBundle mainBundle] loadNibNamed:@"PPAlbumShareActionView" owner:nil options:nil] safeObjectAtIndex:7];
    }

    UIView *displayView = self.delegateViewController.navigationController.view;

    actionView.frame = CGRectMake(0, displayView.height - actionView.height, displayView.width, actionView.height);

    DGPopoverView *popoverView = [[DGPopoverView alloc] initWithContainerView:displayView contentView:actionView options:DGPopoverViewAnimationOptionUpward backgroundStyle:DGPopoverViewBackgroundStyleDimmed];

    __weak typeof(popoverView)weakPopover = popoverView;

    if([actionView respondsToSelector:@selector(wechatButton)]) {
        UIButton *wechatButton = [actionView valueForKey:@"wechatButton"];
        [wechatButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:^{
                [[PPSocializationManager sharedInstance] shareTitle:title subtitle:subtitle url:url image:image type:PPSocializationShareTypeWeixinChat];
            }];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    if([actionView respondsToSelector:@selector(circleButton)]) {
        UIButton *circleButton = [actionView valueForKey:@"circleButton"];
        [circleButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:^{
                [[PPSocializationManager sharedInstance] shareTitle:title subtitle:subtitle url:url image:image type:PPSocializationShareTypeWeixinCircle];
            }];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    if([actionView respondsToSelector:@selector(weiboButton)]) {
        UIButton *weiboButton = [actionView valueForKey:@"weiboButton"];
        [weiboButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:^{
                [[PPSocializationManager sharedInstance] shareTitle:title subtitle:subtitle url:url image:image type:PPSocializationShareTypeWeibo];
            }];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    if([actionView respondsToSelector:@selector(qqButton)]) {
        UIButton *qqButton = [actionView valueForKey:@"qqButton"];
        [qqButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:^{
                [[PPSocializationManager sharedInstance] shareTitle:title subtitle:subtitle url:url image:image type:PPSocializationShareTypeQQChat];
            }];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    if([actionView respondsToSelector:@selector(cancelButton)]) {
        UIButton *cancelButton = [actionView valueForKey:@"cancelButton"];
        [cancelButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:nil];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    [popoverView displayAnimated:YES completion:nil];
}

- (void)reloadDataWithProfiles:(PPAccountProfiles *)profiles {

    _profiles = profiles;
    NSMutableArray *components = [NSMutableArray array];

    if(profiles.gender.integerValue == PPUserGenderMale) {
        [components addSafeObject:@"男，"];
    } else if (profiles.gender.integerValue == PPUserGenderFemale) {
        [components addSafeObject:@"女，"];
    } else {
        [components addSafeObject:@""];
    }

    [components addSafeObject:([[profiles.state validString] length] ? profiles.state : nil)];
    [components addSafeObject:([[profiles.city validString] length] ? profiles.city : nil)];

    NSString *genderInfoString = [components componentsJoinedByString:@" "];
    if ([genderInfoString hasSuffix:@"，"]) {
        genderInfoString = [genderInfoString substringToIndex:[genderInfoString length] - [@"，" length]];
    }
    _genderLabel.text = genderInfoString;

    if(profiles.avatarURLString.length > 0) {
        [profiles.avatarURLString applyToImageView:_avatarView];
    } else {
        _avatarView.image = [UIImage imageNamed:@"icon-person-150"];
    }

    _descLabel.text = profiles.signature;

    if ([profiles.userID isEqualToString:DGCurrentAccount.userID])
    {
        _editButton.backgroundColor = [UIColor whiteColor];
        _editButton.layer.borderColor = [UIColor colorWithRGBHex:0x808080].CGColor;
        [_editButton setTitle:@"编辑个人主页" forState:UIControlStateNormal];
    }
    else if ([profiles.relationship integerValue] == 0 || [profiles.relationship integerValue] == 1)
    {
        _editButton.backgroundColor = [UIColor colorWithRGBHex:0xfede17];
        _editButton.layer.borderColor = [UIColor whiteColor].CGColor;
        [_editButton setTitle:@"已关注" forState:UIControlStateNormal];
    }
    else
    {
        _editButton.layer.borderColor = [UIColor colorWithRGBHex:0x808080].CGColor;
        _editButton.backgroundColor = [UIColor whiteColor];
        [_editButton setTitle:@"+ 关注" forState:UIControlStateNormal];
    }


    NSMutableAttributedString *string1 = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"图册 %li", profiles.albums.integerValue]];
    [string1 setAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRGBHex:0xfede17]}  range:NSMakeRange(3, [string1 length] - 3)];
    _albumLabel.attributedText = string1;

    NSMutableAttributedString *string2 = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"被关注 %li", profiles.fans.integerValue]];
    [string2 setAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRGBHex:0xfede17]}  range:NSMakeRange(3, [string2 length] - 3)];
    _followedLabel.attributedText = string2;

    NSMutableAttributedString *string3 = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"关注 %li", profiles.follows.integerValue]];
    [string3 setAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRGBHex:0xfede17]}  range:NSMakeRange(3, [string3 length] - 3)];
    _followingLabel.attributedText = string3;
}

@end
